<template>
  <div class="carousel-container">
    <div class="header">
      <el-button type="primary" @click="handleAdd">添加轮播图</el-button>
    </div>

    <!-- 轮播图列表 -->
    <el-table
      v-loading="loading"
      :data="carouselList"
      border
      row-key="id"
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="sort" label="排序" width="80" align="center" />
      <el-table-column label="图片" width="200">
        <template #default="{ row }">
          <el-image
            :src="row.image_url"
            :preview-src-list="[row.image_url]"
            fit="contain"
            style="width: 150px; height: 80px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="link" label="链接" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status ? 'success' : 'info'">
            {{ row.status ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="success" link @click="handleToggleStatus(row)">
            {{ row.status ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="图片" prop="image_url">
          <el-upload
            class="carousel-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <el-image
              v-if="form.image_url"
              :src="form.image_url"
              fit="contain"
              style="width: 300px; height: 160px"
            />
            <el-icon v-else class="carousel-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">
            建议尺寸: 750x400像素，支持jpg、png格式，大小不超过2MB
          </div>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="链接" prop="link">
          <el-input v-model="form.link" placeholder="请输入链接地址" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="99" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getCarousels,
  createCarousel,
  updateCarousel,
  deleteCarousel,
  uploadCarouselImage
} from '@/api/carousel'

const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const carouselList = ref([])
const currentId = ref(null)
const formRef = ref(null)

// 上传地址
const uploadAction = `${import.meta.env.VITE_API_URL}/upload/carousel`

// 对话框标题
const dialogTitle = computed(() => currentId.value ? '编辑轮播图' : '添加轮播图')

// 表单数据
const form = reactive({
  image_url: '',
  title: '',
  link: '',
  sort: 0,
  status: 1
})

// 表单校验规则
const rules = {
  image_url: [
    { required: true, message: '请上传轮播图片', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { max: 50, message: '标题长度不能超过50个字符', trigger: 'blur' }
  ],
  link: [
    { required: true, message: '请输入链接地址', trigger: 'blur' }
  ]
}

// 获取轮播图列表
const fetchCarousels = async () => {
  loading.value = true
  try {
    const { data } = await getCarousels()
    carouselList.value = data
  } catch (error) {
    console.error('获取轮播图列表失败:', error)
    ElMessage.error('获取轮播图列表失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.image_url = ''
  form.title = ''
  form.link = ''
  form.sort = 0
  form.status = 1
  currentId.value = null
}

// 添加轮播图
const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

// 编辑轮播图
const handleEdit = (row) => {
  currentId.value = row.id
  Object.assign(form, row)
  dialogVisible.value = true
}

// 切换状态
const handleToggleStatus = async (row) => {
  try {
    await updateCarousel(row.id, {
      status: row.status ? 0 : 1
    })
    ElMessage.success('更新成功')
    fetchCarousels()
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败')
  }
}

// 删除轮播图
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该轮播图吗？', '提示', {
      type: 'warning'
    })
    await deleteCarousel(row.id)
    ElMessage.success('删除成功')
    fetchCarousels()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = /^image\/(jpeg|png)$/.test(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传jpg/png格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (res) => {
  form.image_url = res.data.url
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitLoading.value = true
    if (currentId.value) {
      await updateCarousel(currentId.value, form)
    } else {
      await createCarousel(form)
    }
    
    ElMessage.success(currentId.value ? '更新成功' : '添加成功')
    dialogVisible.value = false
    fetchCarousels()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(currentId.value ? '更新失败:' : '添加失败:', error)
      ElMessage.error(currentId.value ? '更新失败' : '添加失败')
    }
  } finally {
    submitLoading.value = false
  }
}

// 初始化
fetchCarousels()
</script>

<style lang="scss" scoped>
.carousel-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;

  .carousel-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 300px;
    height: 160px;
    
    &:hover {
      border-color: #409eff;
    }
    
    .carousel-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 300px;
      height: 160px;
      line-height: 160px;
      text-align: center;
    }
  }

  .el-upload__tip {
    font-size: 12px;
    color: #606266;
    margin-top: 7px;
  }
}
</style> 